package nl.harmidi.swing;

import java.awt.BorderLayout;
import java.awt.Rectangle;
import java.util.prefs.Preferences;

import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import nl.harmidi.midi.MyMidiEventsLatencyListener;

public class LatencyPanel extends JPanel {

	private static final int MAX_LATENCY = 2000;

	private static final String LATENCY_SLIDER_CURRENT_PREFERENCE = "latency/slider/current";

	private JSlider latencySlider;

	public LatencyPanel() {
		initGui();

	}

	private void initGui() {
		setLayout(new BorderLayout());
		createLatencySlider();
		add(latencySlider, BorderLayout.CENTER);
	}

	private void createLatencySlider() {
		final int synthLatency = (int) MyMidiEventsLatencyListener.getLatency();
		final int storedLatency = Preferences.userRoot().getInt(LATENCY_SLIDER_CURRENT_PREFERENCE, synthLatency);
		final int currentLatency = Math.min(storedLatency, MAX_LATENCY);
		latencySlider = new JSlider(JSlider.HORIZONTAL, 0, MAX_LATENCY, currentLatency);

		latencySlider.setPaintLabels(true);

		latencySlider.setToolTipText("Screen latency in milliseconds");

		// int width = 500;
		// int appWidth = Preferences.userRoot().getInt("frame.width", 1000);
		// width = appWidth - 300;
		// latencySlider.setBounds(new Rectangle(width, (int)
		// latencySlider.getBounds().getHeight()));

		latencySlider.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				JSlider source = (JSlider) e.getSource();
				if (!source.getValueIsAdjusting()) {
					int newLatency = (int) source.getValue();
					MyMidiEventsLatencyListener.setLatency(newLatency);
					Preferences.userRoot().putInt(LATENCY_SLIDER_CURRENT_PREFERENCE, newLatency);
				}
			}
		});

	}
}
